import React, { Component } from "react";
import PubSub from "pubsub-js"
import "./index.css";

export default class List extends Component {

  state = {
    users: [], //初始值为数组\
    isFirst: true, //是否为第一次打开页面
    isLoading: false, //标识是否请求中
    err: '', //存储错误请求信息
    token: null,
  }

  //初始化，开启订阅消息
  componentDidMount() {
    this.token =  PubSub.subscribe('search', (_, data) => {
      console.log(data);
      this.setState(data)
    })
  }

  componentWillUnmount() {
    if(this.token) {
      PubSub.unsubscribe(this.token)
    }
  }

  render() {

    const {users, isFirst, isLoading, err} = this.state;

    return (
      <div className="row">
       {
        isFirst ? <h2>欢迎使用，请输入关键字，点击搜索按钮进行查询</h2> : 
        isLoading ? <h2>Loading......</h2> :
        err ? <h2>{err}</h2> :
        users.map((item) => {
          return (
            <div className="card" key={item.id}>
            <a href={item.html_url} target="_blank" rel="noreferrer">
              <img alt="head_portrait"
                src={item.avatar_url}
                style={{width: '100px'}}/>
            </a>
            <p className="card-text">{item.login}</p>
          </div>
          )
        })
       }
      </div>
    );
  }
}
